//
//  BJFMDBVoiceManager.m
//  BowJoy
//
//  Created by  on 2024/5/23.
//

#import "BJFMDBVoiceManager.h"

@implementation BJFMDBVoiceManager
+ (BJFMDBVoiceManager *)sharedManager{
    static BJFMDBVoiceManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];

    });
    return manager;
}


- (void)creatDatabase{
    //数据库在沙盒中的路径
      NSString * fileName =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) lastObject]stringByAppendingPathComponent:@"voiceOfFMDB.sqlite"];
      
      //创建数据库
      self.database = [[FMDatabase alloc]initWithPath:fileName];
      
      //打开数据库
      if ([self.database open]) {
//          NSLog(@"打开数据库成功");
          //创建表 返回值为BOOL
       
          BOOL flag = [self.database executeUpdate:@"create table if not exists t_voiceOfFMDB (id integer primary key autoincrement,userId text,avatar text,followNum integer,nickname text,title text,content text,anchorUrl text,playurl text,isFriend integer,isLike integer)"];
          if (flag) {
//              NSLog(@"成功建表");
          }else{
//              NSLog(@"失败建表");
          }
          
      //关闭数据库
          [self.database close];
          
      }else{
//          NSLog(@"打开数据库失败");
      }
}


-(void)insertWitModel:(BJAnchorWallModelData *)model{
    if ([self.database open]) {
        //插入数据
        //1.executeUpdate:不确定的参数用？来占位（后面参数必须是oc对象，；代表语句结束）
//        BOOL result = [_db executeUpdate:@"INSERT I NTO t_student (name, age, sex) VALUES (?,?,?)",@"name",@(12),@"24"];
        //2.executeUpdateWithForamat：不确定的参数用%@，%d等来占位 （参数为原始数据类型，执行语句不区分大小写）//
        BOOL result = [self.database executeUpdateWithFormat:@"insert into t_voiceOfFMDB (userId,avatar,followNum,nickname,title,content,anchorUrl,playurl,isFriend,isLike) values (%@,%@,%ld,%@,%@,%@,%@,%@,%d,%d)",model.userId,model.avatar,(long)model.followNum,model.nickname,model.title,model.content,model.anchorUrl,model.playurl,model.isFriend ? 1:0,model.isLike ? 1:0];
        if (result) {
//            NSLog(@"插入成功");
        }else{
//            NSLog(@"插入失败");
        }
          
      }
      [self.database close];
}

// 查询数据

-(NSArray *)queryAllData{
    NSMutableArray *dataList = [[NSMutableArray alloc]init];
    if ([self.database open]) {
            //返回查询数据的结果集
            FMResultSet * resultSet = [self.database executeQuery:@"select * from t_voiceOfFMDB"];
        while ([resultSet next]) {
            BJAnchorWallModelData *model = [[BJAnchorWallModelData alloc]init];
            model.userId = [resultSet stringForColumn:@"userId"];
            model.avatar = [resultSet stringForColumn:@"avatar"];
            model.followNum = [resultSet intForColumn:@"followNum"];
            model.nickname = [resultSet stringForColumn:@"nickname"];
            model.title = [resultSet stringForColumn:@"title"];
            model.content = [resultSet stringForColumn:@"content"];
            model.anchorUrl = [resultSet stringForColumn:@"anchorUrl"];
            model.playurl = [resultSet stringForColumn:@"playurl"];
            model.isFriend = [resultSet intForColumn:@"isFriend"];
            model.isLike = [resultSet intForColumn:@"isLike"];

            [dataList addObject:model];
        }
        
                        
    }
    [self.database close];
    return dataList;

}

// 删除数据
- (void)deleteData {
    if ([self.database open]) {
        NSString *sql = @"delete from t_voiceOfFMDB";
        BOOL res = [self.database executeUpdate:sql];
        if (!res) {
            NSLog(@"error to delete db data");
        } else {
            NSLog(@"success to delete db data");
        }
        [self.database close];
    }
}
- (void)deleteDataWithUserId:(NSString *)userId {
    if ([self.database open]) {
        NSString *sql = [NSString stringWithFormat:@"delete from t_voiceOfFMDB where userId = %@",userId];
        BOOL res = [self.database executeUpdate:sql];
        if (!res) {
            NSLog(@"error to delete db data");
        } else {
            NSLog(@"success to delete db data");
        }
        [self.database close];
    }
}
- (void)uptadeDataWithLike:(NSInteger)isLike andUserId:(NSString *)userId{
    if ([self.database open]) {
        // 2. 创建更新SQL语句
        NSString *updateSQL = [NSString stringWithFormat:@"update t_voiceOfFMDB set isLike = %ld  WHERE userId = %@", (long)isLike,userId];
        
        // 3. 执行更新语句
        BOOL success = [self.database executeUpdate:updateSQL];
        
        if (!success) {
//            NSLog(@"更新失败: %@", [self.database lastErrorMessage]);
        } else {
//            NSLog(@"更新成功");
        }
        
        // 关闭数据库
        [self.database close];
    } else {
//        NSLog(@"无法打开数据库");
    }
}
- (void)uptadeDataWithFollowNum:(NSInteger)followNum andUserId:(NSString *)userId{
    if ([self.database open]) {
        // 2. 创建更新SQL语句
        NSString *updateSQL = [NSString stringWithFormat:@"update t_voiceOfFMDB set followNum = %ld  WHERE userId = %@", (long)followNum,userId];
        
        // 3. 执行更新语句
        BOOL success = [self.database executeUpdate:updateSQL];
        
        if (!success) {
//            NSLog(@"更新失败: %@", [self.database lastErrorMessage]);
        } else {
//            NSLog(@"更新成功");
        }
        
        // 关闭数据库
        [self.database close];
    } else {
//        NSLog(@"无法打开数据库");
    }
}
- (void)uptadeDataWithFrend:(NSInteger)isFrend andUserId:(NSString *)userId{
    if ([self.database open]) {
        // 2. 创建更新SQL语句
        NSString *updateSQL = [NSString stringWithFormat:@"update t_voiceOfFMDB set isFriend = %ld WHERE userId = %@", (long)isFrend, userId];
        
        // 3. 执行更新语句
        BOOL success = [self.database executeUpdate:updateSQL];
        
        if (!success) {
//            NSLog(@"更新失败: %@", [self.database lastErrorMessage]);
        } else {
//            NSLog(@"更新成功");
        }
        
        // 关闭数据库
        [self.database close];
    } else {
//        NSLog(@"无法打开数据库");
    }
}
@end
